import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';

interface College {
  id: number;
  name: string;
  totalStudents: number;
  totalClasses: number;
  totalTeachers: number;
  totalCounselors: number;
  dean: string;
  phone: string;
  email: string;
  address: string;
  description: string;
  status: 'active' | 'inactive';
  createdAt: string;
  updatedAt: string;
}

interface Pagination {
  current: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

const CollegeManagement: React.FC = () => {
  const { t } = useTranslation('college');
  const [colleges, setColleges] = useState<College[]>([]);
  const [pagination, setPagination] = useState<Pagination>({
    current: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0
  });
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingCollege, setEditingCollege] = useState<College | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    totalStudents: 0,
    totalClasses: 0,
    totalTeachers: 0,
    totalCounselors: 0,
    dean: '',
    phone: '',
    email: '',
    address: '',
    description: '',
    status: 'active'
  });

 // 获取学院列表
const fetchColleges = async (page = 1, keyword = '') => {
  setLoading(true);
  try {
    console.log('正在请求学院数据...');
    const response = await fetch(`/api/colleges?page=${page}&pageSize=${pagination.pageSize}&keyword=${keyword}`);
    
    console.log('响应状态:', response.status);
    const result = await response.json();
    console.log('API 返回数据:', result);
    
    if (response.ok) {
      // 调试：检查数据结构
      console.log('result.data:', result.data);
      console.log('result.pagination:', result.pagination);
      
      // 修复：适应不同的数据结构
      const collegesData = result.data || result || [];
      const paginationData = result.pagination || {
        current: page,
        pageSize: pagination.pageSize,
        total: collegesData.length,
        totalPages: Math.ceil(collegesData.length / pagination.pageSize)
      };
      
      setColleges(collegesData);
      setPagination(paginationData);
    } else {
      console.error('获取学院列表失败:', result.error);
      alert('获取学院列表失败: ' + (result.error || '未知错误'));
      setColleges([]);
    }
  } catch (error) {
    console.error('获取学院列表失败:', error);
    alert('获取学院列表失败，请检查网络连接');
    setColleges([]);
  } finally {
    setLoading(false);
  }
};

  useEffect(() => {
    fetchColleges();
  }, []);


  // 搜索处理
  const handleSearch = () => {
    fetchColleges(1, searchKeyword);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchKeyword('');
    fetchColleges(1, '');
  };

  // 分页处理
  const handlePageChange = (page: number) => {
    fetchColleges(page, searchKeyword);
  };

  // 打开添加模态框
  const handleAdd = () => {
    setEditingCollege(null);
    setFormData({
      name: '',
      totalStudents: 0,
      totalClasses: 0,
      totalTeachers: 0,
      totalCounselors: 0,
      dean: '',
      phone: '',
      email: '',
      address: '',
      description: '',
      status: 'active'
    });
    setShowModal(true);
  };

  // 打开编辑模态框
  const handleEdit = (college: College) => {
    setEditingCollege(college);
    setFormData({
      name: college.name,
      totalStudents: college.totalStudents,
      totalClasses: college.totalClasses,
      totalTeachers: college.totalTeachers,
      totalCounselors: college.totalCounselors,
      dean: college.dean,
      phone: college.phone,
      email: college.email,
      address: college.address,
      description: college.description,
      status: college.status
    });
    setShowModal(true);
  };

  // 保存学院
  const handleSave = async () => {
    if (!formData.name.trim()) {
      alert(t('pleaseInput') + t('collegeName'));
      return;
    }

    try {
      const url = editingCollege ? `/api/colleges/${editingCollege.id}` : '/api/colleges';
      const method = editingCollege ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method: method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });

      const result = await response.json();

      if (response.ok) {
        setShowModal(false);
        fetchColleges(pagination.current, searchKeyword);
        alert(editingCollege ? t('updateSuccess') : t('addSuccess'));
      } else {
        alert((editingCollege ? t('updateFailed') + ': ' : t('addFailed') + ': ') + result.error);
      }
    } catch (error) {
      console.error('保存失败:', error);
      alert(t('saveFailed'));
    }
  };

  // 删除学院
  const handleDelete = async (id: number, name: string) => {
    if (!confirm(`${t('confirmDelete')} "${name}" 吗？此操作不可恢复。`)) {
      return;
    }

    try {
      const response = await fetch(`/api/colleges/${id}`, {
        method: 'DELETE',
      });

      const result = await response.json();

      if (response.ok) {
        fetchColleges(pagination.current, searchKeyword);
        alert(t('deleteSuccess'));
      } else {
        alert(t('deleteFailed') + ': ' + result.error);
      }
    } catch (error) {
      console.error('删除失败:', error);
      alert(t('deleteFailed'));
    }
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: name.includes('total') ? parseInt(value) || 0 : value
    }));
  };

  return (
    <div style={{ padding: '20px' }}>
      <h2>{t('title')}</h2>
      
      {/* 搜索和操作栏 */}
      <div style={{ marginBottom: '20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ display: 'flex', gap: '10px' }}>
          <input
            type="text"
            placeholder={t('searchPlaceholder')}
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            style={{ 
              padding: '8px 12px', 
              border: '1px solid #ddd', 
              borderRadius: '4px',
              width: '300px'
            }}
            onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
          />
          <button 
            onClick={handleSearch}
            style={{
              padding: '8px 16px',
              backgroundColor: '#1890ff',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer'
            }}
          >
            {t('common:search')}
          </button>
          <button 
            onClick={handleReset}
            style={{
              padding: '8px 16px',
              backgroundColor: '#f5f5f5',
              color: '#666',
              border: '1px solid #ddd',
              borderRadius: '4px',
              cursor: 'pointer'
            }}
          >
            {t('common:reset')}
          </button>
        </div>
        <button 
          onClick={handleAdd}
          style={{
            padding: '8px 16px',
            backgroundColor: '#52c41a',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer'
          }}
        >
          {t('addCollege')}
        </button>
      </div>

      {/* 学院列表 */}
      <div style={{ background: 'white', borderRadius: '8px', overflow: 'hidden' }}>
        {loading ? (
          <div style={{ textAlign: 'center', padding: '40px' }}>{t('common:loading')}</div>
        ) : (
          <>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ backgroundColor: '#fafafa' }}>
                  <th style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'left' }}>{t('collegeName')}</th>
                  <th style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'center' }}>{t('totalStudents')}</th>
                  <th style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'center' }}>{t('totalClasses')}</th>
                  <th style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'center' }}>{t('totalTeachers')}</th>
                  <th style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'center' }}>{t('totalCounselors')}</th>
                  <th style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'left' }}>{t('dean')}</th>
                  <th style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'left' }}>{t('status')}</th>
                  <th style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'center' }}>{t('operation')}</th>
                </tr>
              </thead>
              <tbody>
                {colleges?.map(college => (
                  <tr key={college.id} style={{ borderBottom: '1px solid #e8e8e8' }}>
                    <td style={{ padding: '12px', border: '1px solid #e8e8e8' }}>
                      <div style={{ fontWeight: 'bold' }}>{college.name}</div>
                      {college.description && (
                        <div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
                          {college.description}
                        </div>
                      )}
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'center' }}>
                      {college.totalStudents}
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'center' }}>
                      {college.totalClasses}
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'center' }}>
                      {college.totalTeachers}
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'center' }}>
                      {college.totalCounselors}
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #e8e8e8' }}>
                      {college.dean}
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #e8e8e8' }}>
                      <span style={{
                        padding: '4px 8px',
                        borderRadius: '4px',
                        fontSize: '12px',
                        backgroundColor: college.status === 'active' ? '#f6ffed' : '#fff2f0',
                        color: college.status === 'active' ? '#52c41a' : '#ff4d4f',
                        border: `1px solid ${college.status === 'active' ? '#b7eb8f' : '#ffccc7'}`
                      }}>
                        {college.status === 'active' ? t('active') : t('inactive')}
                      </span>
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #e8e8e8', textAlign: 'center' }}>
                      <button 
                        onClick={() => handleEdit(college)}
                        style={{
                          padding: '4px 8px',
                          backgroundColor: '#1890ff',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                          marginRight: '8px'
                        }}
                      >
                        {t('common:edit')}
                      </button>
                      <button 
                        onClick={() => handleDelete(college.id, college.name)}
                        style={{
                          padding: '4px 8px',
                          backgroundColor: '#ff4d4f',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer'
                        }}
                      >
                        {t('common:delete')}
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            
             {(!colleges || colleges.length === 0) && (
        <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
          {t('common:noData')}
        </div>
      )}
          </>
        )}
      </div>

      {/* 分页 */}
      {pagination.totalPages > 1 && (
        <div style={{ marginTop: '20px', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <button
            onClick={() => handlePageChange(pagination.current - 1)}
            disabled={pagination.current === 1}
            style={{
              padding: '8px 12px',
              margin: '0 4px',
              backgroundColor: '#f5f5f5',
              border: '1px solid #ddd',
              borderRadius: '4px',
              cursor: pagination.current === 1 ? 'not-allowed' : 'pointer'
            }}
          >
            {t('previousPage')}
          </button>
          
          {Array.from({ length: pagination.totalPages }, (_, i) => i + 1).map(page => (
            <button
              key={page}
              onClick={() => handlePageChange(page)}
              style={{
                padding: '8px 12px',
                margin: '0 4px',
                backgroundColor: page === pagination.current ? '#1890ff' : '#f5f5f5',
                color: page === pagination.current ? 'white' : '#666',
                border: '1px solid #ddd',
                borderRadius: '4px',
                cursor: 'pointer'
              }}
            >
              {page}
            </button>
          ))}
          
          <button
            onClick={() => handlePageChange(pagination.current + 1)}
            disabled={pagination.current === pagination.totalPages}
            style={{
              padding: '8px 12px',
              margin: '0 4px',
              backgroundColor: '#f5f5f5',
              border: '1px solid #ddd',
              borderRadius: '4px',
              cursor: pagination.current === pagination.totalPages ? 'not-allowed' : 'pointer'
            }}
          >
            {t('nextPage')}
          </button>
          
          <span style={{ marginLeft: '16px', color: '#666' }}>
            {t('totalRecords')} {pagination.total} {t('records')}，{t('page')} {pagination.current} / {pagination.totalPages}
          </span>
        </div>
      )}

      {/* 添加/编辑模态框 */}
      {showModal && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0,0,0,0.5)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 1000
        }}>
          <div style={{
            background: 'white',
            borderRadius: '8px',
            padding: '24px',
            width: '600px',
            maxHeight: '80vh',
            overflowY: 'auto'
          }}>
            <h3 style={{ marginBottom: '20px' }}>
              {editingCollege ? t('editCollege') : t('addCollege')}
            </h3>
            
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
              <div>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                  {t('collegeName')} *
                </label>
                <input
                  type="text"
                  name="name"
                  value={formData.name}
                  onChange={handleInputChange}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '4px'
                  }}
                  placeholder={t('pleaseInput') + t('collegeName')}
                />
              </div>
              
              <div>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                  {t('dean')}
                </label>
                <input
                  type="text"
                  name="dean"
                  value={formData.dean}
                  onChange={handleInputChange}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '4px'
                  }}
                  placeholder={t('pleaseInput') + t('dean')}
                />
              </div>
              
              <div>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                  {t('totalStudents')}
                </label>
                <input
                  type="number"
                  name="totalStudents"
                  value={formData.totalStudents}
                  onChange={handleInputChange}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '4px'
                  }}
                  min="0"
                />
              </div>
              
              <div>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                  {t('totalClasses')}
                </label>
                <input
                  type="number"
                  name="totalClasses"
                  value={formData.totalClasses}
                  onChange={handleInputChange}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '4px'
                  }}
                  min="0"
                />
              </div>
              
              <div>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                  {t('totalTeachers')}
                </label>
                <input
                  type="number"
                  name="totalTeachers"
                  value={formData.totalTeachers}
                  onChange={handleInputChange}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '4px'
                  }}
                  min="0"
                />
              </div>
              
              <div>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                  {t('totalCounselors')}
                </label>
                <input
                  type="number"
                  name="totalCounselors"
                  value={formData.totalCounselors}
                  onChange={handleInputChange}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '4px'
                  }}
                  min="0"
                />
              </div>
              
              <div>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                  {t('phone')}
                </label>
                <input
                  type="text"
                  name="phone"
                  value={formData.phone}
                  onChange={handleInputChange}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '4px'
                  }}
                  placeholder={t('pleaseInput') + t('phone')}
                />
              </div>
              
              <div>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                  {t('email')}
                </label>
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleInputChange}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '4px'
                  }}
                  placeholder={t('pleaseInput') + t('email')}
                />
              </div>
              
              <div style={{ gridColumn: '1 / -1' }}>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                  {t('address')}
                </label>
                <input
                  type="text"
                  name="address"
                  value={formData.address}
                  onChange={handleInputChange}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '4px'
                  }}
                  placeholder={t('pleaseInput') + t('address')}
                />
              </div>
              
              <div style={{ gridColumn: '1 / -1' }}>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                  {t('description')}
                </label>
                <textarea
                  name="description"
                  value={formData.description}
                  onChange={handleInputChange}
                  rows={3}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '4px',
                    resize: 'vertical'
                  }}
                  placeholder={t('pleaseInput') + t('description')}
                />
              </div>
              
              <div>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                  {t('status')}
                </label>
                <select
                  name="status"
                  value={formData.status}
                  onChange={handleInputChange}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '4px'
                  }}
                >
                  <option value="active">{t('active')}</option>
                  <option value="inactive">{t('inactive')}</option>
                </select>
              </div>
            </div>
            
            <div style={{ marginTop: '24px', display: 'flex', justifyContent: 'flex-end', gap: '12px' }}>
              <button
                onClick={() => setShowModal(false)}
                style={{
                  padding: '8px 16px',
                  backgroundColor: '#f5f5f5',
                  color: '#666',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                {t('cancel')}
              </button>
              <button
                onClick={handleSave}
                style={{
                  padding: '8px 16px',
                  backgroundColor: '#1890ff',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                {t('common:save')}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default CollegeManagement;